package com.gy.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gy.controller.common.UploadController;
import com.gy.controller.common.UserHolder;
import com.gy.entity.result.PersonalAward;
import com.gy.entity.result.StudentAward;
import com.gy.mapper.StudentAwardMapper;
import com.gy.query.StudentAwardQuery;
import com.gy.result.Result;
import com.gy.service.StudentAwardService;
import com.gy.service.UserService;
import com.gy.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class StudentAwardServiceImpl extends ServiceImpl<StudentAwardMapper, StudentAward> implements StudentAwardService {
    @Autowired
    private UploadController uploadController;

    @Autowired
    private StudentAwardMapper studentAwardMapper;

    @Autowired
    private UserService userService;
    /**
     * 根据openid分页查看某个人的学生获奖信息
     */
    @Override
    public Result<PageVO<StudentAward>> getStudentAward(StudentAwardQuery studentAwardQuery) {
        Long userId = UserHolder.getUser().getUserId();
        if (userId == null) {
            return Result.error("用户登录信息异常");
        }
        Page page = Page.of(studentAwardQuery.getPageNo(), studentAwardQuery.getPageSize());
        //排序条件
        if (!studentAwardQuery.getSortBy().isEmpty() || studentAwardQuery.getIsAsc() != null) {
            page.addOrder(new OrderItem(studentAwardQuery.getSortBy(), studentAwardQuery.getIsAsc()));
        } else {
            //为空，默认按照出版时间排序
            page.addOrder(new OrderItem("id", false));
        }
        //构建查询条件
        LambdaQueryChainWrapper<StudentAward> studentAwardLambdaQueryChainWrapper =
                lambdaQuery().eq(userId != null, StudentAward::getUserId, userId);
        //仅在开始日期和结束日期不为空且有效时添加 between 条件
        if (studentAwardQuery.getStartDate() != null && studentAwardQuery.getEndDate() != null) {
            try {
                Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(studentAwardQuery.getStartDate());
                Date endDate = new SimpleDateFormat("yyyy-MM-dd").parse(studentAwardQuery.getEndDate());
                studentAwardLambdaQueryChainWrapper.between(StudentAward::getAwardTime, startDate, endDate);
            } catch(ParseException e) {        }}

        //添加个人排名分页查询参数
        if (studentAwardQuery.getAuthorRank() != null) {
            studentAwardLambdaQueryChainWrapper.eq(StudentAward::getAuthorRank, studentAwardQuery.getAuthorRank());
        }
        Page<StudentAward> personalAwardPage = studentAwardLambdaQueryChainWrapper.page(page);
        //封装vo结果
        PageVO<StudentAward> vo = new PageVO<>();
        vo.setTotal(personalAwardPage.getTotal());
        vo.setPages(personalAwardPage.getPages());
        List<StudentAward> records = personalAwardPage.getRecords();
        if (CollUtil.isEmpty(records)) {
            vo.setList(Collections.emptyList());
        } else {
            vo.setList(records);
        }
        return Result.success(vo);
    }

    /**
     * 根据id主键删除学生获奖
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result removeStudentAward(Long id) {
        StudentAward studentAward = getById(id);
        if (studentAward == null) {
            return Result.error("学生获奖信息未找到");
        }

        String pdfPath = studentAward.getPdfPath();

        // 检查 pdfPath 是否为空
        if (pdfPath != null && !pdfPath.isEmpty()) {
            try {
                uploadController.deleteFile(pdfPath);
            } catch (Exception e) {
                return Result.error("删除文件失败");
            }
        } else {
            log.warn("pdfPath 为空，无需删除文件");
        }

        boolean removed = removeById(id);
        if (!removed) {
            return Result.error("删除学生获奖信息失败");
        }
        userService.decrementUserAwardStudentCount();
        return Result.success("学生获奖信息删除成功");
    }

    @Override
    public StudentAward getStudentAwardById(Long id) {
        if (id==null) {
            return null;
        }
        return studentAwardMapper.selectStudentAwardById(id);
    }

    @Override
    public Result updateStudentAward(StudentAward studentAward) {
        // 参数验证
        if (studentAward == null) {
            return Result.error("学生奖项信息不能为空");
        }
        if (studentAward.getId() == null) {
            return Result.error("学生奖项ID不能为空");
        }

        try {
            int affectedRows = studentAwardMapper.updateStudentAward(studentAward);
            if (affectedRows > 0) {
                return Result.success(studentAward);
            } else {
                return Result.error("未找到对应的学生奖项信息进行更新");
            }
        } catch (Exception e) {
            // 记录日志
            log.error("更新学生奖项信息时发生异常", e);
            return Result.error("更新学生奖项信息失败");
        }
    }

    /**
     * 新增学生获奖
     * @param studentAward
     * @return
     */
    @Override
    @Transactional
    public Result saveStudentAward(StudentAward studentAward) {
        if (studentAward == null) {
            log.warn("传入的学生奖项对象为空");
            return Result.error("学生奖项对象不能为空");
        }
        try {
            // 设置用户 ID
            studentAward.setUserId(UserHolder.getUser().getUserId());

            boolean save = studentAwardMapper.saveStudentAward(studentAward);
            if (!save) {
                return Result.error("新增失败");
            }
            userService.incrementUserAwardStudentCount();

            return Result.success("新增成功");
        } catch (Exception e) {
            // 记录异常日志
            log.error("保存学生奖项时发生异常", e);
            return Result.error("系统错误，请稍后再试");
        }
    }

    @Override
    public Result getPersonalAwardByIds(Long[] ids) {
        if (ids != null && ids.length > 0) {
            List<StudentAward> personalAwardList = studentAwardMapper.selectStudentAwardBatchIds(Arrays.asList(ids));
            return Result.success(personalAwardList);
        }
        return null;
    }

}
